package com.lengxf.netty.config.initializer;

import com.lengxf.netty.config.handler.TriggerHandler;
import com.lengxf.netty.config.handler.UserWebSocketFrameHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    private final UserWebSocketFrameHandler userWebSocketFrameHandler;

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new IdleStateHandler(5, 0, 0))
                .addLast(new HttpServerCodec())
//                .addLast(new LoggingHandler(LogLevel.INFO))
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(1024 * 1024 * 10))
                .addLast(new WebSocketServerProtocolHandler("/websocket"))
                .addLast(userWebSocketFrameHandler)
                .addLast(new TriggerHandler());
    }


}
